#-*- coding:utf-8 -*-

from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType 
from django.utils import simplejson
from accounts.models import Profile
from upload.models import Image


def check(request, username):
    try:
        User._default_manager.get(username=username)
    except User.DoesNotExist:
        return HttpResponse(simplejson.dumps({"ret":"ok"}))

    return HttpResponse(simplejson.dumps({"ret":"fail"}))


@login_required
def profile(request):
    if request.method == 'GET':
        if request.GET.get("p", "") == "avatar":
            ct = ContentType.objects.get_for_model(request.user)
            imglist = Image.objects.filter(content_type_id=ct.id, object_id=request.user.id)
            if len(imglist) > 0:
                img = imglist[0]
                profile = request.user.profile
                profile.avatar = img.path
                profile.save()

        avatar = request.user.profile.avatar
        return render(request, "accounts/ProfileDetail.html", {"avatar":avatar})

    email = request.POST.get("email", "")
    addr = request.POST.get("addr", "")
    desc = request.POST.get("desc", "")
 
    user = request.user
    user.email = email
    user.save()

    if user.profile :
        profile = user.profile
    else:
        profile = Profile()
        profile.user = user

    profile.email = email
    profile.location = addr 
    profile.desc = desc 
    profile.avatar = "images/avatar-default.gif"
    profile.save()

    avatar = request.user.profile.avatar
    return render(request, "accounts/ProfileDetail.html", {"msg":"设置成功", "avatar":avatar})


def signup_page(request):
    return render(request, "accounts/SignUp.html")


def signup(request):
    if request.method == "GET":
        form = UserCreationForm()
        return render(request, "accounts/SignUpForm.html", {"form":form})
    else:
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save(True)
            user = authenticate(username=user.username, password=form.cleaned_data.get('password1'))
            login(request, user)
            return redirect("/")
        else:
            print form.errors
            return render(request, "accounts/SignUpForm.html", {"form":form})
            
@login_required
def change_password(request):
    return render(request, "accounts/ProfileChangePassword.html")

